package me.zhengjie.utils;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
@DependsOn({"redisUtils"})
public class VxNewMsg {

    @Resource
    private RestTemplate restTemplate;
    @Resource
    private RedisUtils redisUtils;
    @Value("${weixinNew.tokenUrl}")
    private String tokenUrl;
    @Value("${weixinNew.openIdUrl}")
    private String openIdUrl;
    @Value("${weixinNew.phoneUrl}")
    private String phoneUrl;

    @Value("${weixinNew.appID}")
    private String appID;
    @Value("${weixinNew.appSecret}")
    private String appSecret;

    /**
     * 获取微信toekn
     * @return
     */
    public String getVxToken(){
        String jsonStr = restTemplate.getForEntity(tokenUrl+"?appid={1}&secret={2}&grant_type={3}", String.class, appID,appSecret,"client_credential").getBody();
        log.info(jsonStr);
        JSONObject json = JSONUtil.parseObj(jsonStr);
        String accesToken = json.getStr("access_token");
        redisUtils.set("acces_token",accesToken,6000, TimeUnit.SECONDS);
        return accesToken;
    }

    public String vxLogin(String code){
        JSONObject postData = new JSONObject();
        postData.put("appid", appID);
        postData.put("secret", appSecret);
        postData.put("js_code", code);
        postData.put("grant_type", "authorization_code");
        String jsonStr = restTemplate.getForEntity(openIdUrl+"?appid={1}&secret={2}&js_code={3}&grant_type={4}", String.class, appID,appSecret, code,"authorization_code").getBody();
        return jsonStr;

    }
    public String vxPhoneUrl(String code){
        String accesToken;
        if(redisUtils.hasKey("acces_token")){
            log.info("acces_token存在");
            accesToken = (String) redisUtils.get("acces_token");
        }else{
            accesToken = getVxToken();
        }
        log.info("acces_token:"+accesToken);
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("code", code);
        log.info("调用获取信息接口");
        return restTemplate.postForObject(phoneUrl+"?access_token="+accesToken, paramMap, String.class);
    }

}
